import {defineStore} from "pinia";
import {type CacheViewState, type CachedView} from '@/types'

export const useCacheViewStore = defineStore('cachedViews',{
    state: (): CacheViewState => ({
        cachedViews: ['401','403','404','500'], //  keepAlive 缓存页面
    }),
    actions: {
        addCachedView(view: CachedView) {
            const viewName = view.name as string;
            if (this.cachedViews.includes(viewName)) return;
            if (view.meta?.keepAlive) {
                this.cachedViews.push(viewName);
                const maxNum:number = import.meta.env.VITE_KEEP_ALIVE_NUM
                if(this.cachedViews.length>maxNum){
                    this.cachedViews.shift()
                }
            }
        },
        delCachedView(view: CachedView) {
            const viewName = view.name as string;
            return new Promise((resolve) => {
                const index = this.cachedViews.indexOf(viewName);
                index > -1 && this.cachedViews.splice(index, 1);
                resolve([...this.cachedViews]);
            });
        },
        delOtherCachedViews(view: CachedView) {
            const viewName = view.name as string;
            return new Promise((resolve) => {
                const index = this.cachedViews.indexOf(viewName);
                if (index > -1) {
                    this.cachedViews = this.cachedViews.slice(index, index + 1);
                } else {
                    // if index = -1, there is no cached tags
                    this.cachedViews = [];
                }
                resolve([...this.cachedViews]);
            });
        },

        delAllCachedViews() {
            return new Promise(resolve => {
                this.cachedViews = [];
                resolve([...this.cachedViews]);
            });
        },

        //actions end
    }
})